package com.itcast.yygh.hosp.mongo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Optional;

/**
 * 采用mongoRepository的形式测试常用的方法
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Mongo2Test {
    @Autowired
    private UserRepository userRepository;

    //添加数据
    @Test
    public void saveUser(){
        User user = new User();
        user.setAge(20);
        user.setName("张飞");
        user.setEmail("3332200@qq.com");
        user.setCreateDate("2024-03-02");
        //保存
        User users = userRepository.save(user);
        System.out.println(users);
    }
    //根据id查询
    @Test
    public void findById(){
        User user = userRepository.findById("6864a2fa421de32fef25474b").get();
        System.out.println(user);
    }
    //分页数据查询
    @Test
    public void findPage(){
        //1.构建数据的排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "age");
        //2.构建查询分页的对象
        Pageable pageable = PageRequest.of(1,2,sort);

        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        User user = new User();
        user.setName("飞");

        Example example = Example.of(user,matcher);

        Page<User> pages = userRepository.findAll(example, pageable);

        System.out.println(pages.getContent());
    }
    //更新数据
    @Test
    public void updateUser(){
        User user = userRepository.findById("68540af46a051aa5358016d2").get();
        user.setName("关羽飞");

        User user1 = userRepository.save(user);
        System.out.println(user1);
    }
    //使用springData的查询规范进行多条件查询
    @Test
    public void findByNameLike(){
        List<User> users = userRepository.findByNameLike("飞");
        System.out.println(users);
    }

    @Test
    public void findByName(){
        List<User> users = userRepository.findByName("刘备飞");
        System.out.println(users);
    }
    //多个条件查询
    @Test
    public void findByNameAndAge(){
       //List<User> users =  userRepository.findByNameAndAge("张飞",20);
       List<User> users = userRepository.findByNameOrAge("张飞",45);
        System.out.println(users);
    }
}
